package org.boge.sharpdoc.controller;

import com.github.pagehelper.PageInfo;
import org.boge.sharpdoc.config.Settings;
import org.boge.sharpdoc.bean.Banner;
import org.boge.sharpdoc.bean.Customer;
import org.boge.sharpdoc.bean.DocGroup;
import org.boge.sharpdoc.bean.LayuiReturnData;
import org.boge.sharpdoc.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("customer")
public class CustomerController {
    @Autowired
    private DocumentService documentService;
    @Autowired
    private DocGroupService docGroupService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private HttpSession session;
    @Autowired
    private CareService careService;
    @Autowired
    private Settings settings;

    @GetMapping("forgetPage")
    public String forgetPage() {
        return "customer/forget";
    }

    @GetMapping("registerPage")
    public String registerPage() {
        return "customer/register";
    }

    @GetMapping("loginPage")
    public String loginPage() {
        return "customer/login";
    }

    @GetMapping("infoSetPage")
    public String infosetPage() {
        return "customer/infoSet";
    }

    @GetMapping("admin/manageCustomerPage")
    public String manageCustomerPage() {
        return "admin/manageCustomer";
    }

    @GetMapping("index")
    public String index(Model model) {
        //收录文档数量
        model.addAttribute("docNum", documentService.getDocumentCount());
        //注册用户数量
        model.addAttribute("userNum", customerService.getCustomerCount());
        //热门文档
        model.addAttribute("hotdocs", documentService.getHotestDocs());
        //底部热门展示面板
        Map<String, Object> map = new HashMap<>();
        List<DocGroup> firstGroups = docGroupService.getAllFirstStepGroup();
        List<DocGroup> groups;
        for (int i = 0; i < firstGroups.size(); i++) {
            groups = docGroupService.getAllGroupChildren(firstGroups.get(i));
            map.put("g" + i, documentService.findByGroups(groups));
        }
        model.addAttribute("tps", map);
        List<Banner> banners = bannerService.findUseful();
        model.addAttribute("banners", banners);
        return "customer/index";
    }

    @ResponseBody
    @PostMapping("login")
    public LayuiReturnData login(Customer customer) {
        Customer customer_db = customerService.login(customer);
        if (customer_db == null)
            return new LayuiReturnData(0, false, "用户名或密码错误！如果你忘记了你的密码，请通过下方的“忘记密码”进行重置。");
        else if (customer_db.getStatus().equals("禁用")) {
            return new LayuiReturnData(0, false, "该用户已被禁用！");
        } else {
            session.setAttribute("current_customer", customer_db);
            return new LayuiReturnData(0, true);
        }
    }

    @ResponseBody
    @PostMapping("forgetCheck")
    public LayuiReturnData forgetCheck(Long cellphone, String vercodeonpic, String vercodeonphone) {
        session.setAttribute("forgetPhone", cellphone);
        String codeInSession = (String) session.getAttribute("checkCodePhone");
        String piccodeInSession = (String) session.getAttribute("checkCodeImg");
        if (customerService.getCustomerByPhone(cellphone) == null)
            return new LayuiReturnData(0, false, "该手机号尚未注册！");
        else if (codeInSession == null || !codeInSession.equals(vercodeonphone))
            return new LayuiReturnData(0, false, "手机验证码错误！");
        else if (piccodeInSession == null || !piccodeInSession.equalsIgnoreCase(vercodeonpic))
            return new LayuiReturnData(0, false, "图形证码错误！");
        return new LayuiReturnData(0, true);
    }

    @PostMapping("forgetReset")
    @ResponseBody
    public LayuiReturnData forgetReset(String password) {
        Customer customer = new Customer();
        customer.setPhone((Long) session.getAttribute("forgetPhone"));
        customer.setPassword(password);
        customerService.changePassword(customer);
        session.removeAttribute("forgetPhone");
        return new LayuiReturnData(0, true);
    }

    @ResponseBody
    @PostMapping("register")
    public LayuiReturnData register(Customer customer, String vercode) {
        String codeInSession = (String) session.getAttribute("checkCodePhone");
        if (codeInSession == null || !codeInSession.equals(vercode))
            return new LayuiReturnData(0, false, "手机验证码错误！");
        if (customerService.judgeExist(customer))
            return new LayuiReturnData(0, false, "手机号已被注册！如果您之前注册过账户，请通过“<a href='/customer/forgetPage'>忘记密码</a>”进行重置。");
        customerService.register(customer);
        return new LayuiReturnData(0, true);
    }

    @GetMapping("home")
    public String home(Long uid, Model model) {
        Customer s_customer = (Customer) session.getAttribute("current_customer");
        Customer customer;
        if (uid == null)
            // 用户查看自己的主页
            customer = s_customer;
        else {
            // 查看评论用户的主页
            // 由于用户表的主键就是用户注册时的手机号，为防止暴露用户信息（手机号），url链接后面的参数uid是手机号乘以6倍得到
            // 此处恢复手机号，除以6
            customer = customerService.getCustomerByPhone(uid / 6);

            // 查询用户是否已经关注此人
            if (s_customer == null)
                model.addAttribute("iscared", false);
            else
                model.addAttribute("iscared", careService.ifCared(s_customer.getPhone(), customer.getPhone()));
        }
        model.addAttribute("show_customer", customer);
        return "customer/home";
    }

    @PostMapping("bindEmail")
    @ResponseBody
    public LayuiReturnData bindEmail(String emailaddr, String code) {
        String s_code = (String) session.getAttribute("checkCodeMail");
        if (s_code.equals(code)) {
            Customer a_customer = (Customer) session.getAttribute("current_customer");
            a_customer.setEmail(emailaddr);
            session.setAttribute("current_customer", a_customer);
            customerService.bindEmail(a_customer);
            return new LayuiReturnData(0, true, "绑定邮箱成功！");
        } else
            return new LayuiReturnData(0, false, "邮箱验证码错误，请重新输入！");
    }

    @PostMapping("uploadAvatar")
    @ResponseBody
    public LayuiReturnData uploadAvatar(MultipartFile file) throws IOException {
        Customer customer = (Customer) session.getAttribute("current_customer");
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().indexOf('.'));
        String filename = UUID.randomUUID() + suffix;
        File storedFile = new File(settings.getAvatarsDir(), filename);
        file.transferTo(storedFile);
        customer.setAvatar(filename);
        session.setAttribute("current_customer", customer);
        customerService.changeAvatar(customer);
        return new LayuiReturnData(0, true);
    }

    @PostMapping("resetPassword")
    @ResponseBody
    public LayuiReturnData resetPassword(String oldpass, String newpass) {
        Customer customer = (Customer) session.getAttribute("current_customer");
        customer.setPassword(oldpass);
        Customer customer_db = customerService.login(customer);
        if (customer_db == null)
            return new LayuiReturnData(0, false, "密码错误！");
        else {
            customer.setPassword(newpass);
            customerService.changePassword(customer);
            return new LayuiReturnData(0, true);
        }
    }

    @PostMapping("updateInfo")
    @ResponseBody
    public LayuiReturnData updateInfo(Customer customer) {
        Customer a_customer = (Customer) session.getAttribute("current_customer");
        customer.setPhone(a_customer.getPhone());
        customerService.changeInfo(customer);
        // 更新session
        a_customer.setUsername(customer.getUsername());
        a_customer.setGender(customer.getGender());
        a_customer.setSignature(customer.getSignature());
        session.setAttribute("current_customer", a_customer);
        return new LayuiReturnData(0, true);
    }

    @GetMapping("logout")
    public String logout() {
        session.invalidate();
        return "redirect:/customer/index";
    }

    @PostMapping("admin/getAllCustomer")
    @ResponseBody
    public LayuiReturnData getAllCustomer(Integer index, Integer pageSize) {
        PageInfo<Customer> pageInfo = customerService.getAllCustomersByPage(index, pageSize);
        List<Customer> customers = pageInfo.getList();
        for (Customer c : customers) {
            c.setCommentList(null);
            c.setUploadeddoc(null);
        }
        return new LayuiReturnData(0, true, "数据查询成功！", (int) pageInfo.getTotal(), customers);
    }

    @PostMapping("admin/changeStatus")
    @ResponseBody
    public LayuiReturnData changeStatus(Long phone, String status) {
        customerService.changeStatus(phone, status);
        return new LayuiReturnData(0, true, "状态更改成功！");
    }
}